package com.shu.qq.config.security.jwt;

import com.shu.qq.config.security.UserDetailsServiceImpl;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Slf4j
@Component
public class AuthenticationFilter extends OncePerRequestFilter {
    @Resource
    private JwtTokenUtil jwtTokenUtil;
    @Value("${token.header}")
    private String authorization;

    @Override //授权
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.info("检查来自{}的{}请求", request.getRemoteAddr(), request.getRequestURI());
        String jwtToken = request.getHeader(authorization);
        //获取token
        if (StringUtils.hasText(jwtToken)) {
            Claims claims = jwtTokenUtil.getClaimsFromToken(jwtToken);
            String account = jwtTokenUtil.getAccountFromToken(claims);
            List<GrantedAuthority> rolesFromToken = jwtTokenUtil.getRolesFromToken(claims);

            if (jwtTokenUtil.isTokenExpired(claims)) {
                //TODO:token过期，执行重新登录
                log.error("token 过期");
                return;
            }

            //如果可以正确的从JWT中提取用户信息，并且该用户未被授权
            if (account != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                //给使用该JWT令牌的用户进行授权
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(account, null,rolesFromToken);
                //交给spring security管理,在之后的过滤器中不会再被拦截进行二次授权了
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        filterChain.doFilter(request, response);
    }
}
